package com.jwthhealth_pub.health;

import android.animation.ValueAnimator;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.CardView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.jwthhealth_pub.R;
import com.jwthhealth_pub.app.App;
import com.jwthhealth_pub.app.module.ThraPreviewModule;
import com.jwthhealth_pub.common.LogUtil;
import com.jwthhealth_pub.common.base.BasetFragment;
import com.jwthhealth_pub.common.preference.PreferenceKey;
import com.jwthhealth_pub.common.view.JwthHealthMeter;
import com.jwthhealth_pub.health.view.widget.SuperCircleView;
import com.jwthhealth_pub.home.presenter.HealthPresenter;
import com.jwthhealth_pub.old.api.ApiHelper;
import com.jwthhealth_pub.old.common.Constant;
import com.jwthhealth_pub.old.healthyscreening.view.HealthyscreeningAnswerActivity;
import com.jwthhealth_pub.old.individual.module.GetHealthModule;
import com.jwthhealth_pub.old.individual.module.GetPhysical;
import com.jwthhealth_pub.old.individual.module.HeartData;
import com.jwthhealth_pub.old.individual.module.JztzModule;
import com.jwthhealth_pub.old.individual.view.IndividualEvaluateActivity;
import com.jwthhealth_pub.old.individual.view.IndividualHeartActivity;
import com.jwthhealth_pub.old.physicalfitness.view.PhysicalFitnessAnswerActivity;
import com.jwthhealth_pub.old.report.model.resbody.HraDateRes;
import com.jwthhealth_pub.old.report.view.NewReportInfoActivity;
import com.jwthhealth_pub.old.sign.model.LoginModel;
import com.jwthhealth_pub.old.sign.view.SignInActivity;
import com.jwthhealth_pub.old.signutil.model.db.UserInfoDao;
import com.jwthhealth_pub.utils.Contas;
import com.jwthhealth_pub.wristband.broadcast.WristBandReceiver;
import com.jwthhealth_pub.wristband.main.view.WristbandMainActivity;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.jwthhealth_pub.common.LogUtil.makeLogTag;

/**
 * 健康页面
 * Created by yang on 2017/12/8.
 */

public class HealthFragment extends BasetFragment implements HealthPresenter.View {

    public static final String TAG = makeLogTag(HealthFragment.class);

    @BindView(R.id.meter_health)
    JwthHealthMeter meterHealth;
    Unbinder unbinder;
    @BindView(R.id.tv)
    TextView tv_steps;
    @BindView(R.id.superview)
    SuperCircleView mSuperCircleView;
    @BindView(R.id.tv_wenjuang)
    TextView tv_wenjuang;
    @BindView(R.id.tv_shaicha)
    TextView tv_shaicha;
    @BindView(R.id.tv_xinfei)
    TextView tv_xinfei;
    @BindView(R.id.tv_tizhi)
    TextView tv_tizhi;
    @BindView(R.id.tv_nowStep)
    TextView tv_nowStep;
    @BindView(R.id.tv_bloodPressure)
    TextView tv_bloodPressure;
    @BindView(R.id.tv_heartReate)
    TextView tv_heartReate;
    @BindView(R.id.tv_cicre_steps)
    TextView tv_cicre_steps;


    private boolean isLogin;
    @BindView(R.id.cardView_myWristband)
    CardView cardView_myWristband;

    WristBandReceiver mWristBandReceiver;
    String mubiaoValueSteps,ValueSteps,heartReate ,bloodPressure="";
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = View.inflate(getActivity(), R.layout.fragment_health, null);
        unbinder = ButterKnife.bind(this, view);
        initView();

        initTopMeter();

        isLogin = App.preferenceUtil.getBoolean(PreferenceKey.CACHE_TOKEN, false);

        return view;
    }

    private void initTopMeter() {
        ThraPreviewModule.DataBean dataBean = Contas.getObject(getActivity(), ThraPreviewModule.DataBean.class);

        if (dataBean == null) {
            LoginModel.DataBean loginData = Contas.getObject(getActivity(), LoginModel.DataBean.class);
            if (loginData == null) return;

            String uid = loginData.getId();
            if (uid == null) return;
            String token = loginData.getAndroidtoken();
            if (token == null) return;

            Call<ThraPreviewModule> call = ApiHelper.thraPreview(uid, token);
            call.enqueue(new Callback<ThraPreviewModule>() {
                @Override
                public void onResponse(Call<ThraPreviewModule> call, Response<ThraPreviewModule> response) {
                    ThraPreviewModule body = response.body();
                    if (body == null) return;

                    String code = body.getCode();
                    if (code != null && code.equals("0")) {
                        ThraPreviewModule.DataBean data = body.getData();
                        if (data != null)
                            Contas.putObject(getActivity(), data.getClass());

                        meterHealth.setmScore(body.getData().getResult().getTotal());
                    } else {
                        String msg = body.getMsg();
                        if (msg != null)
                            Log.d(TAG, msg);
                    }

                    missLoadProgressbar();
                }

                @Override
                public void onFailure(Call<ThraPreviewModule> call, Throwable t) {
                    Log.e(TAG, t.toString());
                    missLoadProgressbar();
                }
            });
        } else {
            ThraPreviewModule.DataBean.ResultBean result = dataBean.getResult();
            if (result == null) return;

            String total = result.getTotal();
            if (total == null) return;

            meterHealth.setmScore(total);
        }
    }

    private void initView() {
        mubiaoValueSteps = Contas.getName(getActivity(), "mTargetSetp");
        mSuperCircleView.setShowSelect(false);
        ValueAnimator valueAnimator = ValueAnimator.ofInt(0, 100);
        valueAnimator.setTarget(tv_steps);
        valueAnimator.setDuration(2000);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int i = Integer.valueOf(String.valueOf(animation.getAnimatedValue()));
                ValueSteps = Contas.getName(getActivity(),"ValueSteps");
                if (!mubiaoValueSteps.isEmpty()&&!ValueSteps.isEmpty()) {
                    mubiaoValueSteps = mubiaoValueSteps.replace("步", "");
                    int value = Integer.valueOf(ValueSteps);
//                    mSuperCircleView.setSelect((int) (300));
//                     创建一个数值格式化对象
                    NumberFormat numberFormat = NumberFormat.getInstance();
                    // 设置精确到小数点后几位
                    numberFormat.setMaximumFractionDigits(0);
                    String result = numberFormat.format((float) value / (float) Integer.valueOf(mubiaoValueSteps) * 100);
                    mSuperCircleView.setSelect((int) (Integer.valueOf(result) * (i / 100f)));
                    tv_steps.setTextColor(getResources().getColor(R.color.whilelow));
                    tv_steps.setText("已完成" + result + "%");
                } else {
                    tv_steps.setText("已完成" + "一" + "%");
                    tv_steps.setTextColor(getResources().getColor(R.color.whilelow));
                    mSuperCircleView.setSelect(0);
                }

            }
        });
        valueAnimator.start();

        heartReate = Contas.getName(getActivity(),"heartReate");
        bloodPressure = Contas.getName(getActivity(),"bloodPressure");

        tv_nowStep.setText(ValueSteps);
        tv_cicre_steps.setText(ValueSteps + "步");
        tv_bloodPressure.setText(bloodPressure);
        tv_heartReate.setText(heartReate);

    }


    @OnClick(R.id.cardView_myWristband)
    //我的手环点击事件
    public void myWristbandClick() {
        startActivity(new Intent(getActivity(), WristbandMainActivity.class));
    }

    @OnClick({R.id.tv_wenjuang, R.id.tv_shaicha, R.id.tv_xinfei, R.id.tv_tizhi})
    public void clickType(View tview) {
        isLogin = App.preferenceUtil.getBoolean(PreferenceKey.CACHE_TOKEN, false);

        //体适能问卷报告入口
        if (tview.getId() == R.id.tv_wenjuang) {

            //体适能问卷结果
            if (!isLogin) {
                Toast.makeText(getContext(), "请登录", Toast.LENGTH_SHORT).show();
                return;
            }

            LoginModel.DataBean dataBean1 = UserInfoDao.getInstance().queryUserinfoModel();
            if (dataBean1 == null) {
                Toast.makeText(getActivity(), "请先登陆", Toast.LENGTH_SHORT).show();
                return;
            }
            Call<GetPhysical> physical = ApiHelper.getPhysical(dataBean1.getId(), dataBean1.getAndroidtoken());
            physical.enqueue(new Callback<GetPhysical>() {
                @Override
                public void onResponse(@NonNull Call<GetPhysical> call, @NonNull Response<GetPhysical> response) {
                    final GetPhysical body = response.body();
                    if (body == null) return;
                    String code = body.getCode();
                    if (code == null) return;
                    if (code.equals("0")) {
                        Intent intent1 = new Intent(getContext(), PhysicalFitnessAnswerActivity.class);
                        boolean result = false;
                        String result1 = body.getData().getResult();
                        if (result1.equals("1")) {
                            result = true;
                        } else if (result1.equals("0")) {
                            result = false;
                        }
                        intent1.putExtra(Constant.PHYSICAL_ANSERT, result);
                        intent1.putExtra(Constant.ISRETEXT, true);
                        startActivity(intent1);
                        intent1.putExtra(Constant.ISRETEXT, true);
                        startActivity(intent1);
                    } else {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getActivity(), body.getMsg(), Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }

                @Override
                public void onFailure(@NonNull Call<GetPhysical> call, @NonNull Throwable t) {

                }
            });


        }
        //健康筛查入口
        if (tview.getId() == R.id.tv_shaicha) {
            if (!isLogin) {
                Toast.makeText(getActivity(), "请登录", Toast.LENGTH_SHORT).show();
                return;
            }

            LoginModel.DataBean dataBean2 = UserInfoDao.getInstance().queryUserinfoModel();
            if (dataBean2 == null) {
                Toast.makeText(getActivity(), "请先登陆", Toast.LENGTH_SHORT).show();
                return;
            }
            Call<GetHealthModule> health = ApiHelper.getHealth(dataBean2.getId(), dataBean2.getAndroidtoken());
            health.enqueue(new Callback<GetHealthModule>() {
                @Override
                public void onResponse(@NonNull Call<GetHealthModule> call, @NonNull Response<GetHealthModule> response) {
                    final GetHealthModule body = response.body();
                    if (body == null) return;
                    String code = body.getCode();
                    if (code == null) return;
                    if (code.equals("0")) {
                        Intent intent = new Intent(getActivity(), HealthyscreeningAnswerActivity.class);
                        intent.putExtra(Constant.HEALTHYSCREENANSWER, body.getData().getResult());
                        intent.putExtra(Constant.ISRETEXT, true);
                        startActivity(intent);
                    } else {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getActivity(), body.getMsg(), Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }

                @Override
                public void onFailure(@NonNull Call<GetHealthModule> call, @NonNull Throwable t) {
                    Log.e("IndividualInfoFragment", "fail");
                }
            });
        }
        //心肺耐力测试结果入口
        if (tview.getId() == R.id.tv_xinfei) {
            if (!isLogin) {
                Toast.makeText(getActivity(), "请登录", Toast.LENGTH_SHORT).show();
                return;
            }

            LoginModel.DataBean dataBean4 = UserInfoDao.getInstance().queryUserinfoModel();
            if (dataBean4 == null) {
                Toast.makeText(getActivity(), "请先登陆", Toast.LENGTH_SHORT).show();
                return;
            }

            LoginModel.DataBean userinfoModel = UserInfoDao.getInstance().queryUserinfoModel();
            if (userinfoModel != null) {

                Call<HeartData> heartData = ApiHelper.getHeartData(userinfoModel.getId(), userinfoModel.getAndroidtoken());
                heartData.enqueue(new Callback<HeartData>() {
                    @Override
                    public void onResponse(@NonNull Call<HeartData> call, @NonNull Response<HeartData> response) {
                        final HeartData body = response.body();
                        if (body == null) return;
                        String code = body.getCode();
                        if (code == null) return;
                        if (code.equals("0")) {
                            if (body.getData().getList().size() <= 0) {
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(getContext(), "尚未做过该测试", Toast.LENGTH_SHORT).show();
                                    }
                                });
                                return;
                            }
                            Intent intent = new Intent(getActivity(), IndividualHeartActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("data", body.getData());
                            intent.putExtras(bundle);
                            intent.putExtra(Constant.ISRETEXT, true);
                            startActivity(intent);
                        } else if (body.getCode().equals("1")) {
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getActivity(), body.getMsg(), Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    }

                    @Override
                    public void onFailure(@NonNull Call<HeartData> call, @NonNull Throwable t) {

                    }
                });
            } else {
                Toast.makeText(getActivity(), "用户数据异常", Toast.LENGTH_SHORT).show();
            }
        }
        //中医体质测评结果入口
        if (tview.getId() == R.id.tv_tizhi) {

            if (!isLogin) {
                Toast.makeText(getActivity(), "请登录", Toast.LENGTH_SHORT).show();
                return;
            }

            LoginModel.DataBean dataBean3 = UserInfoDao.getInstance().queryUserinfoModel();
            if (dataBean3 == null) {
                Toast.makeText(getActivity(), "请先登陆", Toast.LENGTH_SHORT).show();
                return;
            }

            Call<JztzModule> jztiModule = ApiHelper.getJztiModule(dataBean3.getId(), dataBean3.getAndroidtoken());
            jztiModule.enqueue(new Callback<JztzModule>() {
                @Override
                public void onResponse(@NonNull Call<JztzModule> call, @NonNull Response<JztzModule> response) {
                    final JztzModule body = response.body();
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (body == null) return;
                            String code = body.getCode();
                            if (code == null) return;
                            if (code.equals("0")) {
                                Intent intent2 = new Intent(getActivity(), IndividualEvaluateActivity.class);
                                intent2.putExtra(Constant.ISRETEXT, true);
                                startActivity(intent2);
//                                    List<JztzModule.MsgDataBean> list = body.getData();
//                                    List<Integer> datas = new ArrayList<>();
//                                    if (list.size() == 9) {
//                                        responseTitle.setText("您的体质" + list.get(0).getResult_desc() + "平和质");
//                                    }
//                                    for (int i = 0; i < list.size(); i++) {
//                                        int e = (int) Float.parseFloat(list.get(i).getResult());
//                                        datas.add(e);
//                                    }
//                                    green.setProgress(datas);
//                                    green.start(2);
                            } else {
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(getActivity(), body.getMsg(), Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }

//                        initCharBar(null);
                        }
                    });
                }

                @Override
                public void onFailure(@NonNull Call<JztzModule> call, @NonNull Throwable t) {
                    Log.d("IndividualEvaluateActiv", "error");
                }
            });

        }

    }

    private void notifyData() {
        mWristBandReceiver = new WristBandReceiver();
        mWristBandReceiver.setOnWristBandDataChanged(new WristBandReceiver.onWristBandDataChanged() {
            @Override
            public void onStepChange(List<String> params) {
                Log.i("tag", "step:" + params.get(0) + " kcal:" + params.get(1) + " odo:" + params.get(2));
                if (!params.isEmpty()) {
                    ValueSteps = params.get(0);
                    tv_nowStep.setText(params.get(0));
                    tv_cicre_steps.setText(params.get(0) + "步");

                }
            }

            @Override
            public void onHeartChange(String value) {
                Log.i("tag", "heart:" + value);
            }

            @Override
            public void onBloodPressureChange(ArrayList<String> value) {
                Log.i("tag", "收缩压:" + value.get(0) + " 舒张压:" + value.get(1) + " 心率:" + value.get(2));
                if (!value.isEmpty()) {
                    bloodPressure = value.get(0) + "/" + value.get(1);
                    heartReate = value.get(2);
                    tv_bloodPressure.setText(value.get(0) + "/" + value.get(1));
                    tv_heartReate.setText(value.get(2));
                }



            }

            @Override
            public void onOxyBloodChange(String oxyValue) {
                Log.i("tag", "血氧: " + oxyValue);
                if (!oxyValue.isEmpty()) {
                }

            }

            @Override
            public void onFatifueChange(String fatifue) {
                Log.i("tag", "疲劳度: " + fatifue);
                if (!fatifue.isEmpty()) {
                }
            }

            @Override
            public void onSleepChange(ArrayList<String> sleepValues) {
                Log.i("tag", "睡眠总时间: " + sleepValues.get(0)
                        + "深度睡眠时间" + sleepValues.get(1) + "浅度睡眠时间" + sleepValues.get(2)
                        + "清醒时间" + sleepValues.get(3));

                for (int i=0; i<24; i++) {
//                    Log.d(TAG, "每小时活跃指数" + Log.d(TAG, sleepValues.get(4+i)));
                }
            }
        });
        Log.i("tag", "ddd:");
        IntentFilter wristBandReceiver = new IntentFilter();
        wristBandReceiver.addAction(Constant.PACKAGENAME);
        getActivity().registerReceiver(mWristBandReceiver, wristBandReceiver);
    }

    @Override
    protected void title() {

    }

    @Override
    public void onResume() {
        super.onResume();
        notifyData();
    }

    @Override
    public void onDestroy() {
        getActivity().unregisterReceiver(mWristBandReceiver);
        super.onDestroy();
    }

    private void gotoThraData() {
        LoginModel.DataBean dataBean5 = UserInfoDao.getInstance().queryUserinfoModel();
        if (dataBean5 == null) {
            Toast.makeText(getActivity(), "请先登陆", Toast.LENGTH_SHORT).show();

            Intent intent = new Intent(getActivity(), SignInActivity.class);
            intent.putExtra(Constant.SIGN_JUMP_TOKEN, "0");
            startActivity(intent);
            return;
        }


//                HashMap<String, String> params = new LinkedHashMap<>();
        LoginModel.DataBean userinfoModel = UserInfoDao.getInstance().queryUserinfoModel();
//                params.put("dev", ApiHelper.deviceId);
//                params.put("mac", ApiHelper.macAddress);
//                params.put("uid", userinfoModel.getId());
//                String sign = ReqUtil.getSign(params, userinfoModel.getAndroidtoken());
//                RequestService requestService = RequestHelper.getmRequestHelper();
        Call<HraDateRes> call = ApiHelper.getNewHraDate(userinfoModel.getId(), userinfoModel.getAndroidtoken());
//                Call<HraDate> call = ApiHelper.getHraDate(userinfoModel.getId(), userinfoModel.getAndroidtoken());
        call.enqueue(new Callback<HraDateRes>() {
            @Override
            public void onResponse(@NonNull Call<HraDateRes> call, @NonNull Response<HraDateRes> response) {
                Intent intent3 = new Intent(getActivity(), NewReportInfoActivity.class);
//                        Intent intent3 = new Intent(mActivity, IndividualHealthReportActivity.class);
                HraDateRes body = response.body();
                if (body == null) return;
                if (body.getCode() == null || body.getData() == null) return;
                if (body.getCode().equals("0")) {
                    intent3.putParcelableArrayListExtra("datalist", (ArrayList<? extends Parcelable>) body.getData());
                    intent3.putExtra(Constant.ISRETEXT, true);
                    startActivity(intent3);
//                            progressBar.setVisibility(View.GONE);
                } else {
                    Log.e(TAG, body.getMsg());
                    LogUtil.toast(body.getMsg());
//                            progressBar.setVisibility(View.GONE);
                }
            }

            @Override
            public void onFailure(@NonNull Call<HraDateRes> call, @NonNull Throwable t) {
                Log.e(TAG, t.toString());
//                        progressBar.setVisibility(View.GONE);
            }
        });
    }

    @OnClick({R.id.btn_health_gotothra, R.id.meter_health})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_health_gotothra:
            case R.id.meter_health:
                gotoThraData();
                break;
        }
    }

    @Override
    public void onDestroyView() {
        Contas.putName(getActivity(),"ValueSteps",ValueSteps);
        Contas.putName(getActivity(),"heartReate",heartReate);
        Contas.putName(getActivity(),"bloodPressure",bloodPressure);
        super.onDestroyView();


    }
}
